<template>
  <div>
    <Card _Title="用户信息" :_Size="16"></Card>
    <a-form ref="formDataRef" :model="formData" :style="{ width: '600px' }" @submit="handleSubmit">
      <a-form-item label="头像">
        <div>
          <div class="mb_10">
            <a-avatar :size="88" v-if="formData.face"><img alt="avatar" :src="formData.face"/></a-avatar>
            <a-avatar v-else :size="88"><img alt="avatar" src="/src/assets/images/default.png"/></a-avatar>
          </div>
          <a-upload ref="uploadRef" :action="uploadFile" :headers="{ accessToken: accessToken }" :show-file-list="false"
                    :onSuccess="uploadSuccess" :onError="handleError" @before-upload="beforeUpload">
            <template #upload-button>
              <a-space><a-button>头像上传</a-button></a-space>
            </template>
          </a-upload>
        </div>
      </a-form-item>
      <a-form-item field="nickName" label="昵称" :rules="[REQUIRED, VARCHAR20]">
        <a-input style="width: 191px;" v-model="formData.nickName" placeholder=""></a-input>
      </a-form-item>
      <a-form-item label="生日">
        <a-date-picker type="date" placeholder="选择您的生日" v-model="formData.birthday"></a-date-picker>
      </a-form-item>
      <a-form-item label="性别">
        <a-radio-group v-model="formData.sex" type="button">
          <a-radio :value="1">男</a-radio>
          <a-radio :value="0">女</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item>
        <a-button html-type="submit" type="primary" status="danger" class="mr_10" :loading="loading">保存修改</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import { REQUIRED, VARCHAR20 } from '@/utils/validator';
  import storage from '@/utils/storage';
  import uploadFile from '@/api/common';
  import {  handleError, beforeUpload, accessToken } from '@/utils/upload';
  import { editMemberInfo } from '@/api/account';

  const formDataRef = ref();
  const formData = ref<any>({});
  const loading = ref(false);

  // 上传成功回调
  const uploadSuccess = (val: any) => {
    formData.value.face = val.response.result;
  };
  // 保存修改
  const handleSubmit = async () => {
    const auth = await formDataRef.value?.validate();
    if (!auth) {
      let params = {
        birthday: formData.value.birthday,
        face: formData.value.face,
        nickName: formData.value.nickName,
        sex: formData.value.sex
      };
      editMemberInfo(params).then(res => {
        if (res.data.success) {
          Message.success('修改个人资料成功');
          storage.setUserInfo(res.data.result);
        }
      })
    }
  };

  onMounted(() => {
    if (storage.getUserInfo()) {
      formData.value = JSON.parse(storage.getUserInfo());
    }
  })
</script>

<style scoped lang="less">

</style>
